//
//  WFCLoginViewController.m
//  Wildfire Chat
//
//  Created by WF Chat on 2017/7/9.
//  Copyright © 2017年 WildFireChat. All rights reserved.
//

#import "WFCLoginViewController.h"
#import <WFChatClient/WFCChatClient.h>
#import <WFChatUIKit/WFChatUIKit.h>
#import "AppDelegate.h"
#import "WFCBaseTabBarController.h"
#import "WFCResetPasswordViewController.h"
#import "MBProgressHUD.h"
#import "UILabel+YBAttributeTextTapAction.h"
#import "WFCPrivacyViewController.h"
#import "AppService.h"
#import "UIColor+YH.h"
#import "UIFont+YH.h"
#import "YGExtendChain.h"
#import "SDAutoLayout.h"


@interface WFCLoginViewController () <UITextFieldDelegate>
@property (strong, nonatomic) UILabel *hintLabel;
@property (strong, nonatomic) UITextField *userNameField;
@property (strong, nonatomic) UITextField *passwordField;
@property (strong, nonatomic) UIButton *loginBtn;

@property (strong, nonatomic) UILabel *passwordLabel;


@property (strong, nonatomic) UIView *userNameLine;
@property (strong, nonatomic) UIView *passwordLine;

@property (strong, nonatomic) UIButton *sendCodeBtn;
@property (nonatomic, strong) NSTimer *countdownTimer;
@property (nonatomic, assign) NSTimeInterval sendCodeTime;
@property (nonatomic, strong) UILabel *privacyLabel;
@property (nonatomic, strong)UIView * inputView ;

@property (strong, nonatomic) UIButton *switchButton;
@property (strong, nonatomic) UIButton *registerButton;
@property (strong, nonatomic) UIImageView *img2;


@end

@implementation WFCLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    CGFloat wsf =  ZmScreenWidth_N()   ;
    CGFloat ws1 = wsf  / 360 * 269;
 
    UIImageView *head = [[UIImageView alloc]init];
    [self.view addSubview:head];
    head.image = [UIImage imageNamed:@"lo_top"];
    head.sd_layout.rightEqualToView(self.view).topEqualToView(self.view).widthIs(ZmScreenWidth_N()).heightIs(ws1);
    
    
    
    UIImageView *lo_hi = [[UIImageView alloc]init];
    [self.view addSubview:lo_hi];
    lo_hi.image = [UIImage imageNamed:@"lo_hi"];
    lo_hi.sd_layout.centerXEqualToView(self.view).topSpaceToView(self.view, 160).widthIs(96).heightIs(96);
    
    
    
    
    UILabel *lab1 = [[UILabel alloc] init ];
    [lab1 setText:@"欢迎登录TL畅聊"];
    lab1.textAlignment = NSTextAlignmentLeft;
    lab1.font = [UIFont boldSystemFontOfSize:20];
    [self.view addSubview:lab1];
    lab1.sd_layout.centerXEqualToView(lo_hi).topSpaceToView(lo_hi, 20 ).autoHeightRatio(0);
    [lab1 setSingleLineAutoResizeWithMaxWidth:200];
    
    
 
    UIView *view_bag = [[UIView alloc]init];
    [self.view addSubview:view_bag];
    view_bag.sd_layout.leftEqualToView(self.view).topSpaceToView(head, 0).widthIs(ZmScreenWidth_N()).bottomEqualToView(self.view);
    view_bag.sh_chain_extend.backgroundColorClear().roundSize(20);
    
    
    
    
    
    
//    UILabel *lab2 = [[UILabel alloc] init ];
//    [lab2 setText:@"TL畅聊"];
//    lab2.textAlignment = NSTextAlignmentLeft;
//    lab2.font = [UIFont boldSystemFontOfSize:24];
//    lab2.textColor = [ UIColor colorWithHexString:@"#016EFF"];
//    [self.view addSubview:lab2];
//    lab2.sd_layout.leftSpaceToView(lab1, 2).centerYEqualToView(lab1).autoHeightRatio(0);
//    [lab2 setSingleLineAutoResizeWithMaxWidth:200];
 
    
    
    NSString *savedName = [[NSUserDefaults standardUserDefaults] stringForKey:@"savedName"];
   
    CGRect bgRect = self.view.bounds;
    CGFloat paddingEdge = 16;
    CGFloat inputHeight = 60;
    CGFloat hintHeight = 26;
    CGFloat topPos = 30 ;
    
    self.hintLabel = [[UILabel alloc] initWithFrame:CGRectMake(paddingEdge, topPos, bgRect.size.width - paddingEdge - paddingEdge, hintHeight)];
    [self.hintLabel setText:@"手机号登录"];
    self.hintLabel.textAlignment = NSTextAlignmentLeft;
    self.hintLabel.font = [UIFont boldSystemFontOfSize:24];
    self.hintLabel.hidden = YES;
    
    
    topPos += hintHeight + 50;
    
    UIView *userNameContainer = [[UIView alloc] initWithFrame:CGRectMake(paddingEdge, topPos, bgRect.size.width - 2 * paddingEdge, inputHeight)];
    
    UILabel *userNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 52, inputHeight - 1)];
    userNameLabel.text = @"手机号";
    userNameLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
    
    self.userNameLine = [[UIView alloc] initWithFrame:CGRectMake(0, inputHeight - 1, userNameContainer.frame.size.width, 1.f)];
    self.userNameLine.backgroundColor = [UIColor colorWithHexString:@"0xd4d4d4"];
    
    
    self.userNameField = [[UITextField alloc] initWithFrame:CGRectMake(87, 0, userNameContainer.frame.size.width - 87, inputHeight - 1)];
    self.userNameField.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:15];
    self.userNameField.placeholder = @"请输入手机号(仅支持中国大陆号码)";
    self.userNameField.returnKeyType = UIReturnKeyNext;
    self.userNameField.keyboardType = UIKeyboardTypePhonePad;
    self.userNameField.delegate = self;
    self.userNameField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.userNameField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
 
    UIView * view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    self.userNameField.leftView = view1;
    self.userNameField.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *img1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_1"]];
    [view1 addSubview:img1];
    img1.sd_layout.centerXEqualToView(view1).centerYEqualToView(view1).widthIs(20).heightIs(20);
    
    
    
    topPos += inputHeight + 1;

    UIView *passwordContainer  = [[UIView alloc] initWithFrame:CGRectMake(paddingEdge, topPos, bgRect.size.width - paddingEdge * 2, inputHeight)];
    self.passwordLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 52, inputHeight - 1)];
    self.passwordLabel.text = @"验证码";
    self.passwordLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16];
    
    
    self.passwordLine = [[UIView alloc] initWithFrame:CGRectMake(0, inputHeight - 1, passwordContainer.frame.size.width, 1.f)];
    self.passwordLine.backgroundColor = [UIColor colorWithHexString:@"0xd4d4d4"];
    
    
    self.passwordField = [[UITextField alloc] initWithFrame:CGRectMake(87, 0, passwordContainer.frame.size.width - 87 - 72, inputHeight - 1)];
    self.passwordField.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:15];
    self.passwordField.placeholder = @"请输入验证码";
    self.passwordField.returnKeyType = UIReturnKeyDone;
    self.passwordField.keyboardType = UIKeyboardTypeNumberPad;
    self.passwordField.delegate = self;
    self.passwordField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self.passwordField addTarget:self action:@selector(textDidChange:) forControlEvents:UIControlEventEditingChanged];
//    self.passwordField.leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 10, 20)];
//    self.passwordField.leftViewMode = UITextFieldViewModeAlways;
 
    UIView * view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 20)];
    self.passwordField.leftView = view2;
    self.passwordField.leftViewMode = UITextFieldViewModeAlways;
    
    UIImageView *img2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"login_2"]];
    [view2 addSubview:img2];
    img2.sd_layout.centerXEqualToView(view2).centerYEqualToView(view2).widthIs(20).heightIs(20);
    self.img2 = img2;
    
    
    self.sendCodeBtn = [[UIButton alloc] initWithFrame:CGRectMake(passwordContainer.frame.size.width - 72, (inputHeight - 1 - 23) / 2.0, 72, 23)];
    [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    self.sendCodeBtn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleRegular size:14];
//    self.sendCodeBtn.layer.borderWidth = 1;
    self.sendCodeBtn.layer.cornerRadius = 8;
//    self.sendCodeBtn.layer.borderColor = [UIColor colorWithHexString:@"0x191919"].CGColor;
   
    [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];
//    [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"0x171717"] forState:UIControlStateSelected];
    [self.sendCodeBtn addTarget:self action:@selector(onSendCode:) forControlEvents:UIControlEventTouchDown];
    self.sendCodeBtn.backgroundColor = [UIColor colorWithHexString:@"#F7F7F7"];
    
//    self.sendCodeBtn.sh_chain_extend.backgroundImage_state([UIImage imageWithColor:[UIColor colorWithHexString:@"#016EFF"]], 0) .backgroundImage_state([UIImage imageWithColor:[UIColor colorWithHexString:@"#D8D8D8"]], UIControlStateDisabled) ;
    self.sendCodeBtn.enabled = NO;
    

    topPos += 60;
    
    topPos += 8;
    
    self.switchButton = [[UIButton alloc] initWithFrame:CGRectMake(paddingEdge, topPos, 150, 40)];
    [self.switchButton setTitle:@"使用用户密码登录" forState:UIControlStateNormal];
    self.switchButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    self.switchButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [self.switchButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
    [self.switchButton addTarget:self action:@selector(onSwitchLoginType:) forControlEvents:UIControlEventTouchDown];
    
    self.registerButton = [[UIButton alloc] initWithFrame:CGRectMake(bgRect.size.width - paddingEdge - 100, topPos, 100, 40)];
    [self.registerButton setTitle:@"注册" forState:UIControlStateNormal];
    self.registerButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    self.registerButton.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
    [self.registerButton addTarget:self action:@selector(onRegister:) forControlEvents:UIControlEventTouchDown];
    
    topPos += 40;
    topPos += 31;
    
    self.loginBtn = [[UIButton alloc] initWithFrame:CGRectMake(paddingEdge + 25, topPos, bgRect.size.width - paddingEdge * 2 - 50, 50)];
    [self.loginBtn addTarget:self action:@selector(onLoginButton:) forControlEvents:UIControlEventTouchDown];
    self.loginBtn.layer.masksToBounds = YES;
    self.loginBtn.layer.cornerRadius = 5.f;
    [self.loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    self.loginBtn.backgroundColor = [UIColor colorWithHexString:@"#E2E2E2"];
    [self.loginBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];
    self.loginBtn.titleLabel.font = [UIFont pingFangSCWithWeight:FontWeightStyleMedium size:16];
    self.loginBtn.enabled = NO;
    
//    [view_bag addSubview:self.hintLabel];
//    self.hintLabel.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(view_bag, 30).autoHeightRatio(0);
//    [self.hintLabel setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];
    
    
//    [view_bag addSubview:userNameLabel];
//    userNameLabel.sd_layout.leftEqualToView(self.hintLabel).topSpaceToView(self.hintLabel, 30).autoHeightRatio(0);
//    [userNameLabel setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];
    
    
    [view_bag addSubview:self.userNameField];
    self.userNameField.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(view_bag, 64).heightIs(45).widthIs(ZmScreenWidth_N() - 60);
    self.userNameField.sh_chain_extend.roundSize(5).backgroundColor([UIColor colorWithHexString:@"#F7F7F7"]);
    
    
//    [view_bag addSubview:self.userNameLine];
 
//    [view_bag addSubview:passwordContainer];
//    [view_bag addSubview:self.passwordLabel];
//    self.passwordLabel.sd_layout.leftEqualToView(self.hintLabel).topSpaceToView(self.userNameField, 15).autoHeightRatio(0);
//    [self.passwordLabel setSingleLineAutoResizeWithMaxWidth:ZmScreenWidth_N()];

    
    [view_bag addSubview:self.passwordField];
    self.passwordField.sd_layout.leftSpaceToView(view_bag, 30).topSpaceToView(self.userNameField, 20).heightIs(45).widthIs(ZmScreenWidth_N() - 60);
    self.passwordField.sh_chain_extend.roundSize(5).backgroundColor([UIColor colorWithHexString:@"#F7F7F7"]);

    
//    [view_bag addSubview:self.passwordLine];
    [view_bag addSubview:self.sendCodeBtn];
    self.sendCodeBtn.sd_layout.rightEqualToView(self.passwordField).widthIs(94).heightIs(45).centerYEqualToView(self.passwordField);
    self.sendCodeBtn.sh_chain_extend.round();
    
    
    [view_bag addSubview:self.switchButton];
    self.switchButton.sd_layout.leftSpaceToView(view_bag, 30).widthIs(140).heightIs(40).topSpaceToView(self.passwordField, 15);

    
    [view_bag addSubview:self.registerButton];
    self.registerButton.sd_layout.rightSpaceToView(view_bag, 20).widthIs(50).heightIs(40).centerYEqualToView(self.switchButton);

    
    
    [view_bag addSubview:self.loginBtn];
    self.loginBtn.sd_layout.topSpaceToView(self.passwordField, 114).heightIs(45).widthIs(ZmScreenWidth_N() - 60).centerXEqualToView(view_bag);
    self.loginBtn.sh_chain_extend.roundSize(5);


    
    self.userNameField.text = savedName;
    
//    [head addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetKeyboard:)]];

    [view_bag addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(resetKeyboard:)]];
    
    self.privacyLabel = [[UILabel alloc] initWithFrame:CGRectMake(16, view_bag.bounds.size.height - 40 - [WFCUUtilities wf_safeDistanceBottom], view_bag.bounds.size.width-32, 40)];
    self.privacyLabel.textAlignment = NSTextAlignmentCenter;
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"登录即代表你已同意《TL畅聊用户协议》和《TL畅聊隐私政策》" attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:10],
                                                                                                                     NSForegroundColorAttributeName : [UIColor darkGrayColor]}];
    [text setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:10],
                          NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#016EFF"]} range:NSMakeRange(9, 10)];
    [text setAttributes:@{NSFontAttributeName : [UIFont systemFontOfSize:10],
                          NSForegroundColorAttributeName : [UIColor colorWithHexString:@"#016EFF"]} range:NSMakeRange(20, 10)];
    self.privacyLabel.attributedText = text ;
    __weak typeof(self)ws = self;
    [self.privacyLabel yb_addAttributeTapActionWithRanges:@[NSStringFromRange(NSMakeRange(9, 10)), NSStringFromRange(NSMakeRange(20, 10))] tapClicked:^(UILabel *label, NSString *string, NSRange range, NSInteger index) {
//        WFCPrivacyViewController * pvc = [[WFCPrivacyViewController alloc] init];
//        pvc.isPrivacy = (range.location == 19);
//        [ws.navigationController pushViewController:pvc animated:YES];
    }];
    
    [view_bag addSubview:self.privacyLabel];
    self.privacyLabel.sd_layout.bottomSpaceToView(view_bag, 40).widthIs(ZmScreenWidth_N()).heightIs(40).centerXEqualToView(view_bag);
    
    
    
    [self setIsPwdLogin:self.isPwdLogin];
}

- (void)setIsPwdLogin:(BOOL)isPwdLogin {
    _isPwdLogin = isPwdLogin;
    CGRect bgRect = self.view.bounds;
    CGRect pwdFeildFrame = self.passwordField.frame;
    CGFloat paddingEdge = 16;
    CGFloat pwdFeildWidth = bgRect.size.width - paddingEdge * 2 - 87;
    if (isPwdLogin) {
        self.img2.image = [UIImage imageNamed:@"login_2"];

        self.hintLabel.text = @"密码登录";
        self.passwordLabel.text = @"密  码 ";
        self.sendCodeBtn.hidden = YES;
        self.passwordField.placeholder = @"请输入密码";
        self.passwordField.keyboardType = UIKeyboardTypeASCIICapable;
        self.passwordField.secureTextEntry = YES;
        self.passwordField.text = nil;
        if (self.passwordField.isFirstResponder) {
            [self.passwordField resignFirstResponder];
            [self.passwordField becomeFirstResponder];
        }
        [self.switchButton setTitle:@"使用短信验证码登录" forState:UIControlStateNormal];
    } else {
        self.img2.image = [UIImage imageNamed:@"login_3"];

        self.hintLabel.text = @"短信验证码登录";
        self.passwordLabel.text = @"验证码";
        self.sendCodeBtn.hidden = NO;
        self.passwordField.placeholder = @"请输入验证码";
        self.passwordField.keyboardType = UIKeyboardTypeNumberPad;
        self.passwordField.secureTextEntry = NO;
        self.passwordField.text = nil;
        if (self.passwordField.isFirstResponder) {
            [self.passwordField resignFirstResponder];
            [self.passwordField becomeFirstResponder];
        }
        [self.switchButton setTitle:@"使用用户密码登录" forState:UIControlStateNormal];
        pwdFeildWidth -= 72;
    }
    pwdFeildFrame.size.width = pwdFeildWidth;
    self.passwordField.frame = pwdFeildFrame;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if(self.isKickedOff) {
        self.isKickedOff = NO;
        UIAlertController *actionSheet = [UIAlertController alertControllerWithTitle:nil message:@"您的账号已在其他手机登录" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];

        [actionSheet addAction:actionCancel];
        
        [self presentViewController:actionSheet animated:YES completion:nil];
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)onSwitchLoginType:(id)sender {
    if (!self.isPwdLogin) {
      
        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
//        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#A8AFB3"] forState:UIControlStateNormal];
        self.registerButton.userInteractionEnabled = YES;
    }
//    [UIView animateWithDuration:0.5 animations:^{
        self.isPwdLogin = !self.isPwdLogin;
//    }];
    

}

- (void)onRegister:(id)sender {
    
    if (self.isPwdLogin) {
        [([UIApplication sharedApplication].keyWindow ?: [UIApplication sharedApplication].windows.firstObject) addSubview:self.inputView];
        self.inputView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));

        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#A8AFB3"] forState:UIControlStateNormal];
        self.registerButton.userInteractionEnabled = NO;
    } else {
         
        
        [self onLoginButton:nil];

        
    }
  
    
}

- (void)on1Register  {
    [self removeMain];

    self.isPwdLogin = NO;

}
- (UIView *)inputView{
    if (!_inputView) {
        _inputView = [[UIView alloc]init];
        
        _inputView.sh_chain_extend.backgroundColor([UIColor colorWithHexString:@"#3F3C41" alpha:0.57]);

        UIView *view = [[UIView alloc]init];
        [_inputView addSubview:view];
        view.sd_layout.centerXEqualToView(self.inputView).centerYEqualToView(self.inputView).offset(-25) .widthIs(ZmScreenWidth_N() - 130) ;
        view.sh_chain_extend.backgroundColorWhite().roundSize(25);

        
        
      
        UIButton *lab1 = [[UIButton alloc]init];
        
        [view addSubview:lab1];
        lab1.sd_layout.topSpaceToView(view, 25).leftSpaceToView(view, 15).heightIs(30).widthIs(80);
 
        lab1.sh_chain_extend.title(@" 提示！").titleColorBlack().font_size_bold(18).image_loc(@"lo_tip").modeFit() ;
        
         
        
        
        
        UILabel *btn1 = [[UILabel alloc]init];
        [view addSubview:btn1];
        btn1.sd_layout.topSpaceToView(lab1, 20).autoHeightRatio(0).leftSpaceToView(view, 20);
        [btn1 setSingleLineAutoResizeWithMaxWidth: ZmScreenWidth_N() - 130 - 40];
        btn1.sh_chain_extend.titleColor([UIColor colorWithHexExtendString:@"#9E9E9E"]).title(@"使用短信验证码登录，将会为 您创建账户，请使用短信验证码登录") .font([UIFont pingFangSCWithWeight:FontWeightStyleRegular size:15]) ;
         
//        [btn1 jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
//            
// 
//            [ZX_weakSelf removeMain];
//            [ZX_weakSelf outLogin:gestureRecoginzer.view];
//
//        }];
        
      
        UIButton *btn1_c = [[UIButton alloc]init];
        [view addSubview:btn1_c];
        btn1_c.sd_layout.rightSpaceToView(view, 20).topSpaceToView(btn1, 25).heightIs(30).widthIs(40);
        btn1_c.sh_chain_extend.title(@"确认").titleColor([UIColor colorWithHexString:@"#016EFF"]).font([UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16]).addTarget_action(self, @selector(on1Register));
      
        
        
        UIButton *btn1_d = [[UIButton alloc]init];
        [view addSubview:btn1_d];
        btn1_d.sd_layout.rightSpaceToView(btn1_c, 20).topSpaceToView(btn1, 25).heightIs(30).widthIs(40);
        btn1_d.sh_chain_extend.title(@"取消").titleColor([UIColor colorWithHexExtendString:@"#9E9E9E"]).font([UIFont pingFangSCWithWeight:FontWeightStyleRegular size:16]).addTarget_action(self, @selector(removeMain));
        
        
        
        
        [view setupAutoHeightWithBottomView:btn1_c bottomMargin:26];
        
     
//        [btn1_c jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
//            
// 
//            [ZX_weakSelf removeMain];
//       
//        }];
        
    }
    return _inputView;
}
- (void)removeMain
{

 
   [UIView animateWithDuration:0.15 animations:^{

       self.inputView.alpha = 0 ;
   } completion:^(BOOL finished) {
       self.inputView.hidden = YES;
       [self.inputView removeFromSuperview];
       self.inputView  = nil;

   }];
}
- (void)onSendCode:(id)sender {
    self.sendCodeBtn.enabled = NO;
    [self.sendCodeBtn setTitle:@"短信发送中" forState:UIControlStateNormal];
    __weak typeof(self)ws = self;
    [[AppService sharedAppService] sendLoginCode:self.userNameField.text success:^{
       [ws sendCodeDone:YES];
    } error:^(NSString * _Nonnull message) {
        [ws sendCodeDone:NO];
        
        
        
    }];
}

- (void)updateCountdown:(id)sender {
    int second = (int)([NSDate date].timeIntervalSince1970 - self.sendCodeTime);
    [self.sendCodeBtn setTitle:[NSString stringWithFormat:@"%ds", 60-second] forState:UIControlStateNormal];
    if (second >= 60) {
        [self.countdownTimer invalidate];
        self.countdownTimer = nil;
        [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
        self.sendCodeBtn.enabled = YES;
    }
}
- (void)sendCodeDone:(BOOL)success {
  //  [self.userNameField resignFirstResponder];

    //[self.passwordField resignFirstResponder];

    dispatch_async(dispatch_get_main_queue(), ^{
        if (success) {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"发送成功";
          //  //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            self.sendCodeTime = [NSDate date].timeIntervalSince1970;
            self.countdownTimer = [NSTimer scheduledTimerWithTimeInterval:1
                                                                target:self
                                                                 selector:@selector(updateCountdown:)
                                                              userInfo:nil
                                                               repeats:YES];
            [self.countdownTimer fire];
            
            
            [hud hideAnimated:YES afterDelay:1.f];
        } else {
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.mode = MBProgressHUDModeText;
            hud.label.text = @"发送失败";
//            //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
            [hud hideAnimated:YES afterDelay:1.f];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.sendCodeBtn setTitle:@"获取验证码" forState:UIControlStateNormal];
                self.sendCodeBtn.enabled = YES;
            });
        }
    });
}

- (void)resetKeyboard:(id)sender {
    [self.userNameField resignFirstResponder];
    self.userNameLine.backgroundColor = [UIColor grayColor];
    [self.passwordField resignFirstResponder];
    self.passwordLine.backgroundColor = [UIColor grayColor];
}

- (void)onLoginButton:(id)sender {
    NSString *user = self.userNameField.text;
    NSString *password = self.passwordField.text;
  
    if (!user.length || !password.length) {
        return;
    }
    
    [self resetKeyboard:nil];
    
  MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
  hud.label.text = @"登录中...";
  [hud showAnimated:YES];
    
      void(^errorBlock)(int errCode, NSString *message) = ^(int errCode, NSString *message) {
          NSLog(@"login error with code %d, message %@", errCode, message);
        dispatch_async(dispatch_get_main_queue(), ^{
          [hud hideAnimated:YES];
          
          MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
          hud.mode = MBProgressHUDModeText;
            hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
          hud.label.text = @"登录失败";
//          //hud.offset = CGPointMake(0.f, MBProgressMaxOffset);
          [hud hideAnimated:YES afterDelay:1.f];
        });
      };
      
      void(^successBlock)(NSString *userId, NSString *token, BOOL newUser, NSString *resetCode) = ^(NSString *userId, NSString *token, BOOL newUser, NSString *resetCode) {
          [[NSUserDefaults standardUserDefaults] setObject:user forKey:@"savedName"];
          [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"savedToken"];
          [[NSUserDefaults standardUserDefaults] setObject:userId forKey:@"savedUserId"];
          [[NSUserDefaults standardUserDefaults] synchronize];
          
          
          //需要注意token跟clientId是强依赖的，一定要调用getClientId获取到clientId，然后用这个clientId获取token，这样connect才能成功，如果随便使用一个clientId获取到的token将无法链接成功。
          [[WFCCNetworkService sharedInstance] connect:userId token:token];
          
            [hud hideAnimated:YES];
            WFCBaseTabBarController *tabBarVC = [WFCBaseTabBarController new];
            [UIApplication sharedApplication].delegate.window.rootViewController =  tabBarVC;
          if (newUser == YES ) {
              if ([tabBarVC.childViewControllers.firstObject isKindOfClass:[UINavigationController class]]) {
                  WFCResetPasswordViewController *vc = [[WFCResetPasswordViewController alloc] init];
                  vc.resetCode = resetCode;
                  vc.hidesBottomBarWhenPushed = YES;
                  UINavigationController *nav = (UINavigationController *)tabBarVC.childViewControllers.firstObject;
                  dispatch_async(dispatch_get_main_queue(), ^{
                      [nav pushViewController:vc animated:YES];
                  });
              }
          }
      };
      
      
      if (self.isPwdLogin) {
          [[AppService sharedAppService] loginWithMobile:user password:password success:^(NSString *userId, NSString *token, BOOL newUser) {
              successBlock(userId, token, newUser, nil);
          } error:errorBlock];
      } else {
          [[AppService sharedAppService] loginWithMobile:user verifyCode:password success:successBlock error:errorBlock];
      }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField == self.userNameField) {
        [self.passwordField becomeFirstResponder];
    } else if(textField == self.passwordField) {
        [self onLoginButton:nil];
    }
    return NO;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.userNameField) {
        self.userNameLine.backgroundColor = [UIColor colorWithHexString:@"#016EFF"];
        self.passwordLine.backgroundColor = [UIColor grayColor];
    } else if (textField == self.passwordField) {
        self.userNameLine.backgroundColor = [UIColor grayColor];
        self.passwordLine.backgroundColor = [UIColor colorWithHexString:@"#016EFF"];
    }
    return YES;
}
#pragma mark - UITextInputDelegate
- (void)textDidChange:(id<UITextInput>)textInput {
    if (textInput == self.userNameField) {
        [self updateBtn];
    } else if (textInput == self.passwordField) {
        [self updateBtn];
    }
}

- (void)updateBtn {
    if ([self isValidNumber]) {
        if (!self.countdownTimer) {
            self.sendCodeBtn.enabled = YES;
            [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];
//            self.sendCodeBtn.layer.borderColor = [UIColor colorWithRed:0.1 green:0.27 blue:0.9 alpha:0.9].CGColor;
        } else {
            self.sendCodeBtn.enabled = NO;
//            self.sendCodeBtn.layer.borderColor = [UIColor colorWithHexString:@"0x191919"].CGColor;
            [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];
//            [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateSelected];
        }
        
        if ([self isValidCode]) {
            [self.loginBtn setBackgroundColor:[UIColor colorWithHexString:@"#016EFF"]];
            [self.loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            self.loginBtn.enabled = YES;
            
            if (!self.isPwdLogin) {
              
                [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
        //        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#A8AFB3"] forState:UIControlStateNormal];
                self.registerButton.userInteractionEnabled = YES;
            }else{
                
            }
            
        } else {
            [self.loginBtn setBackgroundColor:[UIColor colorWithHexString:@"#E2E2E2"]];
            [self.loginBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];

            self.loginBtn.enabled = NO;
            
            if (!self.isPwdLogin) {
                //                [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
                [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#A8AFB3"] forState:UIControlStateNormal];
                self.registerButton.userInteractionEnabled = NO;

             
            }else{
                [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
        //        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#A8AFB3"] forState:UIControlStateNormal];
                self.registerButton.userInteractionEnabled = YES;
                
            }
            
        }
    } else {
        
        if (!self.isPwdLogin) {
            //                [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
   
            
        }else{
            [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#016EFF"] forState:UIControlStateNormal];///蓝
    //        [self.registerButton setTitleColor:[UIColor colorWithHexString:@"#A8AFB3"] forState:UIControlStateNormal];
            self.registerButton.userInteractionEnabled = YES;
            
        }
        self.sendCodeBtn.enabled = NO;
        [self.sendCodeBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];
        
        [self.loginBtn setBackgroundColor:[UIColor colorWithHexString:@"#E2E2E2"]];
        [self.loginBtn setTitleColor:[UIColor colorWithHexString:@"#A7A7A7"] forState:UIControlStateNormal];

        self.loginBtn.enabled = NO;
    }
}

- (BOOL)isValidNumber {
    NSString * MOBILE = @"^((1[23456789]))\\d{9}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    if (self.userNameField.text.length == 11 && ([regextestmobile evaluateWithObject:self.userNameField.text] == YES)) {
        return YES;
    } else {
        return NO;
    }
}

- (BOOL)isValidCode {
    if (self.passwordField.text.length >= 1) {
        return YES;
    } else {
        return NO;
    }
}
@end
